package com.starbaba.core.web.taglib.ace.component;

import java.io.Writer;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.components.Component;

import com.starbaba.core.web.constant.WebConstants;
import com.opensymphony.xwork2.util.ValueStack;


public class AceMsgComponent extends Component {
	
	private HttpServletRequest request;
	
	private String key;
	
	private static final String ERROR_MSG_HTML =  "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"><i class=\"ace-icon fa fa-times\"></i></button><strong><i class=\"ace-icon fa fa-check\"></i>操作失败:</strong>&nbsp;&nbsp;&nbsp;#message#<br></div>";
	private static final String SUCCESS_MSG_HTML = "<div class=\"alert alert-block alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"><i class=\"ace-icon fa fa-times\"></i></button><p><strong><i class=\"ace-icon fa fa-check\"></i>操作成功:</strong>&nbsp;&nbsp;&nbsp;#message#</p></div>";

	public AceMsgComponent(ValueStack stack, HttpServletRequest request) {
		super(stack);
		this.request = request;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean start(Writer writer) {
		boolean result = super.start(writer); 
		try {
			if(StringUtils.isNotBlank(key)){
				String message = (String)request.getAttribute(key);
				if(StringUtils.isNotBlank(message)){
					writer.write(message);
				}
				return true;
			}
			/**
			 * 向页面输出错误信息   
			 */
			List<String> errorMsgList = (List<String>)request.getAttribute(WebConstants.ERROR_MESSAGE);
			if(null != errorMsgList && errorMsgList.size() > 0){
				StringBuffer errorMsgBuf = new StringBuffer("");
				for(String errorMsg : errorMsgList){
					errorMsgBuf.append(StringUtils.replace(ERROR_MSG_HTML, "#message#", errorMsg));
				}
				writer.write(errorMsgBuf.toString());
			}
			/**
			 * 向页面输出正确信息
			 */
			List<String> successMsgList = (List<String>)request.getAttribute(WebConstants.DEFAULT_MESSAGE);
			if(null != successMsgList && successMsgList.size() > 0){
				StringBuffer successMsgBuf = new StringBuffer("");
				for(String successMsg : successMsgList){
					successMsgBuf.append(StringUtils.replace(SUCCESS_MSG_HTML, "#message#", successMsg));
				}
				writer.write(successMsgBuf.toString());
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
        return result;
    }

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

}
